package cn.web.provider.dubboConfig.mbean;

import javax.management.MBeanServer;
import javax.management.ObjectName;
import java.lang.management.ManagementFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

public class ShutdownLatch implements ShutdownLatchMBean {

    protected AtomicBoolean running = new AtomicBoolean(false);
    private long checkIntervalInSeconds = 10L;
    private String domain = "com.test";

    public ShutdownLatch() {
    }

    public ShutdownLatch(String domain) {
        this.domain = domain;
    }

    public void await() throws Exception {
        if (this.running.compareAndSet(false, true)) {
            //获取MBeanServer  如果没有MBean server存在那么下面会自动调用ManagementFactory.createMBeanServer()
            MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
            //包名加 类名 创建一个ObjectName
            mBeanServer.registerMBean(this, new ObjectName(this.domain, "name", "ShutdownLatch"));

            while(this.running.get()) {
                TimeUnit.SECONDS.sleep(this.checkIntervalInSeconds);
            }
        }

    }

    @Override
    public String shutdown() {
        if (this.running.compareAndSet(true, false)) {
            return "Shutdown signal sent, shutting down...";
        }
        return "Shutdown signal had been sent, no need again and again...";
    }
}
